/**
 * 查看订单详情弹窗
 */
import React, { useEffect, useState, useRef } from 'react';
import { Descriptions, Modal, Divider, Button, Row, Col } from 'antd'
import { getZcOrderDetail } from '@/services/order/api';
import { isNull, showMsg } from '@/utils/utils';
// @ts-ignore
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { print } from '@/utils/utils';
import { useModel } from 'umi';

const { info } = Modal;


const OnceOrderDetail: React.FC<any> = (props) => {
  const {
    record = {},
    handleModalVisible,
    isPrint
  } = props;
  const [loading, setLoading] = useState(false);
  // 是否弹出打印窗口
  const [printing, setPrinting] = useState(false);
  //  一次性订单详情
  const [detail, setDetail] = useState<ORDERAPI.OnceOrderItem>({});
  // 付款码
  const [showQrCode, setShowQrCode] = useState(false);

  const { initialState } = useModel('@@initialState');

  const columns: ProColumns<any>[] = [
    {
      title: '商品名称',
      dataIndex: 'goods_name'
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      hideInTable: printing,
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name'
    },
    {
      title: '单价',
      dataIndex: 'price',
      valueType: 'money',
      align: 'right',
    },
    {
      title: '数量',
      dataIndex: 'goods_num',
      align: 'right',
    },
    {
      title: '价格',
      dataIndex: 'goods_total_price',
      valueType: 'money',
      align: 'right',
      hideInTable: printing,
    },
  ]

  useEffect(() => {
    init(isPrint);
  }, [record]);

  const init = (readyPrint?: boolean) => {
    if (record.order_id) {
      setLoading(true);
      getZcOrderDetail(record.order_id).then((res) => {
        setLoading(false);
        setDetail(res);
        // 弹出打印窗口
        if (readyPrint) {
          printPage();
        }
      }).catch(error => {
        setLoading(false);
        showMsg(error?.data?.errmsg);
      });
    }
  }

  // 获得商品数量/退款数量
  const getGoodsNum = (list, key) => {
    let count = 0;
    (list || []).map(item => {
      count += item[key];
    })
    return count;
  }

  // 打印
  const printPage = () => {
    setPrinting(true);
    setTimeout(() => {
      print(document.querySelector('.order-modal .ant-modal-body'), {
        // printZoom: 0.9
        size: 'portrait'
      });
      setTimeout(() => {
        setPrinting(false);
      }, 5000);
    }, 500);
  }

  // console.log('ygdata', ygData)

  return <>
    <Modal
      title="查看订单"
      wrapClassName="order-modal"
      width="90%"
      bodyStyle={{ height: printing ? 'auto' : window.innerHeight - 185, overflowY: printing ? 'auto' : 'scroll' }}
      maskClosable={false}
      confirmLoading={loading}
      onCancel={() => { handleModalVisible(false) }}
      footer={[
        <Button key="back" onClick={() => {
          handleModalVisible(false);
        }}>
          关闭
        </Button>,
        <Button style={{ marginLeft: 10 }} key="print" type="primary" onClick={printPage}>
          打印订单
        </Button>
      ]}
      visible>

      {/* 打印的dom信息 */}
      <div className="order-modal-content" style={{ width: printing ? '80%' : '100%', transform: printing ? 'scale(0.85)' : 'scale(1)', transformOrigin: '0 0' }}>
        {/* <div className="order-modal-content"> */}
        <div className='print_yes print_title'>订单详情</div>
        <Divider className='print_yes' style={{ paddingBottom: 15 }} />
        <div style={{ fontSize: 12, fontWeight: 'bold' }}>1.患者信息</div>
        <Divider />
        <div style={{ display: 'flex' }}>
          <Descriptions column={printing ? 1 : 4} style={{ flex: 1 }}>
            <Descriptions.Item label="身份证/住院号">{detail.identity_no}{!isNull(detail.identity_no) && !isNull(detail.admission_num) ? ` / ` : ''}{detail.admission_num}</Descriptions.Item>
            <Descriptions.Item label="患者姓名">{detail.patient_name}</Descriptions.Item>
            <Descriptions.Item label="归属科室">{detail.create_dept_name}</Descriptions.Item>
            <Descriptions.Item label="开单人">{detail.apply_oper_name || '无'}</Descriptions.Item>
          </Descriptions>
          {
            printing &&
            <Descriptions style={{ flex: '0.5', float: 'right' }} className='print_ewm'>
              <Descriptions.Item label="订单二维码">
                <img src={detail.qr_code} width={120} height={120} />
              </Descriptions.Item>
            </Descriptions>
          }
        </div>
        <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>2.商品信息</div>
        <Divider />
        <ProTable<STOCKGOODSAPI.GoodsItem>
          rowKey="record_id"
          style={{ marginTop: 14 }}
          options={false}
          search={false}
          columns={columns}
          pagination={false}
          dataSource={detail.goodsList}
          bordered />
        <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>3.订单汇总</div>
        <Divider />
        <Row wrap={false}>
          <Col span={!printing ? 18 : 24}>
            <Descriptions column={2} className='noBottom'>
              <Descriptions.Item label="订单编号">{detail.order_id}</Descriptions.Item>
              <Descriptions.Item label="创建时间" /* style={{ width: printing ? '40%' : 'auto' }} */>{detail.create_date + ' ' + detail.create_time}</Descriptions.Item>
              <Descriptions.Item label="商品数量">
                <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{getGoodsNum(detail.goodsList, 'goods_num')}</span>（件）
              </Descriptions.Item>
              <Descriptions.Item label="订单金额">{detail.total_price}（元）</Descriptions.Item>
            </Descriptions>
          </Col>
          {
            !printing && <Col span={6} style={printing ? { flex: '0 0 auto', width: 122 } : {}}>
              {<Descriptions column={1}>
                <Descriptions.Item label="订单二维码" className={printing ? 'qrCodeLabel' : ''}>
                  <img src={detail.qr_code} width={120} height={120} />
                </Descriptions.Item>
              </Descriptions>}
            </Col>
          }
        </Row>
      </div>
    </Modal>
  </>
}
export default OnceOrderDetail;
